<script setup lang="ts">
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
import { ElMessage, ElMessageBox } from "element-plus"
import examDetail from '#/assets/images/exam/exam.svg'
import ExamChart from './exam-chart.vue';
import { ExamScoreDialog } from './index'
import { FileText } from '@vben/icons';
import { getExamInfoWithSituationApi, getExamScoreByOrganizationApi, publishExamScoreApi, createCertificateApi } from "#/api/manage/examination-mgr"
import { $t } from '@vben/locales';
import type { ExamDetail, OrganizationScoreDTO } from "./examination"
import dayjs from 'dayjs';
import { useTabs } from '@vben/hooks';
import { statusBg } from '../const'
const { setTabTitle } = useTabs();

const router = useRouter()
const examScoreDialogRef = ref<InstanceType<typeof ExamScoreDialog> | null>(null)
const examId = ref(route?.query?.id ?? '')
const resLoading = ref(false)
const activeOrg = ref<OrganizationScoreDTO>()
const activeTabs = ref()
const examInfo = ref<ExamDetail>()
const total = ref(0)
const infoLoading = ref(false)
const perforTableData = ref()
const pageData = reactive({
  curPage: 1,
  pageSize: 10,
});

const onQuery = () => {
  const params = {
    idsList: examId.value
  } as any;
  infoLoading.value = true
  getExamInfoWithSituationApi(params).then((res) => {
    let { data = [] } = res
    examInfo.value = data[0] ?? null
    console.log(examInfo.value)
    if (examInfo.value && examInfo.value?.organizationScoreDTOList?.length > 0) {
      const org = examInfo.value?.organizationScoreDTOList[0] as OrganizationScoreDTO ?? null
      activeOrg.value = org
      activeTabs.value = org?.id ?? null
      getExamScore()
    }
  }).finally(() => {
    infoLoading.value = false;
  })
}

const getExamScore = () => {
  const params = {
    examId: examId.value,
    organizationId: activeTabs.value,
    curPage: pageData.curPage,
    pageSize: pageData.pageSize
  } as any;
  infoLoading.value = true
  getExamScoreByOrganizationApi(params).then((res) => {
    let { data = [], pageInfo = { totalRows: 0 } } = res
    nextTick(() => {
      total.value = pageInfo?.totalRows ?? 0
      perforTableData.value = data ?? []
    })
  }).finally(() => {
    infoLoading.value = false;
  })
}


const handleSizeChange = (val: number) => {
  pageData.pageSize = val
  pageData.curPage = 1
  getExamScore()
}
const handleCurrentChange = (val: number) => {
  pageData.curPage = val
  getExamScore()
}

const batchCorrect = (userId?: any) => {
  console.log(userId)
  router.push({
    query: {
      id: examInfo.value?.id,
      orgId: examInfo.value?.organizationIdList && examInfo.value?.organizationIdList.length > 0 ? examInfo.value?.organizationIdList[0] : '',
      userId
    },
    name: 'ExaminationCorrection'
  }).then(() => {
    setTabTitle(examInfo.value?.name ?? '')
  });
}

const scoreEntry = () => {
  examScoreDialogRef.value?.inint()
}

const releaseRes = () => {
  ElMessageBox.confirm(
    $t('exam.askExamPushTxt'),
    $t('common.tipTxt'),
    {
      confirmButtonText: $t('common.submitTxt'),
      cancelButtonText: $t('common.cancelTxt'),
      type: 'warning',
    }
  )
    .then(() => {
      const params = {
        examId: examId.value,
        organizationId: activeTabs.value
      }
      resLoading.value = false;
      publishExamScoreApi(params).then((res) => {
        if (res) {
          getExamScore()
          ElMessage.success($t('common.handleSuccessTxt'))
          createCertificate()
        }
      }).finally(() => {
        resLoading.value = false;
      })
    })
    .catch(() => { })

}

const createCertificate = () => {
  ElMessageBox.confirm(
    $t('exam.askCreateCertTxt'),
    $t('common.tipTxt'),
    {
      confirmButtonText: $t('common.submitTxt'),
      cancelButtonText: $t('common.cancelTxt'),
      type: 'warning',
    }
  )
    .then(() => {
      const params = {
        orgId: activeTabs.value,
        userIds: null,
        certificationId: examInfo.value?.certificationId
      }
      resLoading.value = false;
      createCertificateApi(params).then((res) => {
        if (res) {
          getExamScore()
          ElMessage.success($t('common.handleSuccessTxt'))
        }
      }).finally(() => {
        resLoading.value = false;
      })
    })
    .catch(() => { })
}

const updatePerfor = () => {
  onQuery()
}

onMounted(() => {
  onQuery()
})

const getExamTime = (data: any) => {
  if (!data?.beginTime) return '--'
    const time = new Date(data?.beginTime).getTime() + data.duration * 60 * 1000
    const endTime = dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    return `${data.beginTime}~${endTime}`
}

const handleTabChange = (val: string) => {
  console.log(val)
  if (!!val) {
    getExamScore()
  }
}

</script>
<template>
  <div class="p-[24px] min-h-screen" v-loading="infoLoading">
    <!-- Top exam information -->
    <div class="flex items-center bg-white rounded-lg p-[24px] mb-4">
      <img :src="examDetail" class="w-12 h-12 mr-[12px]" />
      <div>
        <div class="flex items-center mb-[5px]">
          <div class="text-[20px] font-bold mr-[16px]">{{ examInfo?.name }}</div>
          <div class="text-pink-600 px-5 py-2 rounded-[4px] text-[12px]"
            :class="[examInfo?.status === 'begin' || examInfo?.status === 'end' ? 'bg-[#F3F3F3]' : 'bg-[#e5484d33]']">
            <span class="text-[#191919] mr-[5px]">{{ $t('exam.examTime') }}</span>
            <span class="font-[500]"
              :class="[examInfo?.status === 'begin' || examInfo?.status === 'end' ? 'text-[#595959]' : 'text-[#E5484D]']">{{
                getExamTime(examInfo) }}</span>
          </div>
        </div>
        <div class="flex flex-wrap items-center text-[14px] mt-1">
          <div class="mr-[24px]">
            <span class="text-[#595959] mr-[8px]">{{ $t('exam.examCourseLabel') }}</span>
            <span class="text-[#191919]">{{ examInfo?.courseName ?? '--' }}</span>
          </div>
          <div class="mr-[24px]">
            <span class="text-[#595959] mr-[8px]">{{ $t('exam.linkCert') }}</span>
            <span class="text-[#191919]">{{ examInfo?.certificationName ?? '--' }}</span>
          </div>
          <div>
            <span class="text-[#595959] mr-[8px]">{{ $t('exam.examPlace') }}</span>
            <span class="text-[#191919]">{{ examInfo?.location ?? '--' }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Switch the organization -->
    <el-tabs :lazy="true" v-model="activeTabs" type="card" class="demo-tabs" @tab-change="handleTabChange">
      <el-tab-pane v-for="item in examInfo?.organizationScoreDTOList ?? []" :key="item.id" :label="item.name"
        :name="item.id">
        <!-- Overview of the Examination -->
        <div class="bg-white rounded-lg mb-4 ">
          <ExamChart :activeOrg="activeOrg" :examId="examId"></ExamChart>
        </div>
        <!-- Candidate performance -->
        <div class="bg-white rounded-lg mb-4">
          <div class="border-b border-color:#DCDFE6 p-[24px] mb-[15px]">
            <div class="text-base font-bold">{{ $t('exam.candidatePerforTxt') }}</div>
          </div>
          <div class="p-[24px] pt-[0px]">
            <el-button class="mb-[16px]" v-if="examInfo?.mode === 'online'" :disabled="examInfo?.status !== 'end'"
              type="primary" @click="batchCorrect">{{
                $t('exam.toCorrect') }}</el-button>
            <el-button class="mb-[16px]" v-if="examInfo?.mode === 'offline'" :disabled="examInfo?.status !== 'end'"
              @click="scoreEntry">{{ $t('exam.scoreEntryTxt') }}</el-button>
            <el-button :loading="resLoading" class="mb-[16px]" :disabled="examInfo?.status !== 'end'"
              @click="releaseRes">{{ $t('exam.resultsAnnounceTxt') }}</el-button>
            <el-table :data="perforTableData" max-height="400px">
              <el-table-column prop="index" :label="$t('common.numberIdxTxt')" type="index" width="60" />
              <el-table-column prop="userName" :label="$t('common.nameTxt')" />
              <el-table-column prop="phone" :label="$t('common.phoneTxt')" />
              <el-table-column prop="status" :label="$t('common.statusTxt')">
                <template #default="{ row }">
                  <div class="flex items-center">
                    <span class="inline-block w-[8px] h-[8px] rounded-[4px] mr-[5px]"
                      :style="{ 'background-color': statusBg[row.status as keyof typeof statusBg] }"></span>
                    <span>{{ row.status ? $t(`exam.${row.status}Txt`) : '--' }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="score" :label="$t('exam.examGradesTxt')">
                <template #default="{ row }">
                  <span>{{ row.score || '--' }}</span>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common.handleTxt')" width="80">
                <template #default="{ row }">
                  <div v-if="examInfo?.mode === 'online'">
                    <el-tooltip effect="dark" :content="$t('common.detailTxt')" :show-after="1000" placement="top">
                      <el-button
                        :disabled="examInfo?.status !== 'end' || row?.status === 'absent' || row?.status === 'publish'"
                        :icon="FileText" size="small" link @click="batchCorrect(row.userId)" />
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              class="pagination pt-[15px]" size="small" layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[10, 20, 50, 100]" :page-size="pageData.pageSize" :total="total"></el-pagination>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- examination description -->
    <div class="bg-white rounded-lg">
      <div class="border-b border-color:#DCDFE6 p-[24px] mb-[15px]">
        <div class="text-base font-bold">{{ $t('exam.examDes') }}</div>
      </div>
      <div class="p-[24px] pt-[0px]">
        <div v-html="examInfo?.description" class="text-[14px] text-[#191919] leading-[28px] whitespace-pre-wrap"></div>
      </div>
    </div>
    <ExamScoreDialog ref="examScoreDialogRef" :examId="examId" :organizationId="activeTabs"
      @updatePerfor="updatePerfor">
    </ExamScoreDialog>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-segmented) {
  padding: 0px;
  --el-border-radius-base: 8px;
}

:deep(.el-tabs__header) {
  border: none;
}

:deep(.el-tabs--card>.el-tabs__header .el-tabs__nav) {
  background-color: #DCDFE6;
  border-bottom: 1px solid var(--el-border-color-light);
  border-radius: 8px;
}

:deep(.el-tabs--card>.el-tabs__header .el-tabs__item) {
  border: none;
  border-radius: 8px;
}

:deep(.el-tabs--card>.el-tabs__header .el-tabs__item.is-active) {
  background-color: #0067D1;
  color: #fff;
}

:deep(.el-tabs__nav-scroll) {
  border-radius: 8px;
}

:deep(.el-tabs__nav-next, .el-tabs__nav-prev) {
  line-height: 36px;
}
</style>
